<template>
    <div id="app">
      <table border="2" cellspacing="0">
        <tr>
          <td><input type="checkbox" v-model="addm" /></td>
          <td>商品名称</td>
          <td>商品价格</td>
          <td>商品数量</td>
          <td>商品小计</td>
        </tr>
        <tr v-for="(item, idx) of sd" :key="item.name">
          <td><input type="checkbox" v-model="item.che" /></td>
          <td>{{ item.name }}</td>
          <td>{{ item.price }}</td>
          <td>
            <input type="number" v-model="item.num" @input="fun(item.num, idx)" />
          </td>
          <td>{{ item.price * item.num }}</td>
        </tr>
      </table>
      <div>总计：{{ add }}</div>
    </div>
  </template>
  <script>
  export default {
    name: "App",
    data() {
      return {
        sd: [
          { name: "ipple", price: 3000, num: 1, che: "ture" },
          { name: "小米", price: 5000, num: 2, che: "ture" },
          { name: "华为", price: 4000, num: 3, che: "ture" },
        ],
      };
    },
    computed: {
      add: function () {
        let sum = 0;
        this.sd.forEach((item) => {
          if (item.che) {
            sum += item.price * item.num;
          }
        });
        return sum;
      },
  
      addm: {
        // 全选
        get() {
          return this.sd.every((item) => {
            return item.che;
          });
        },
  
        // 修改
        set(newVal) {
          // 看一下newVal的值
          // console.log(newVal)
            if(newVal){
              this.sd.forEach((item) => {
                item.che = newVal;
              });
            }else{
              this.sd.forEach((item) => {
                item.che = newVal;
              })
          }
  
        },
      },
    },
  
    methods: {
      fun(num, idx) {
        // 把input输入框上获取的字符串转换为数类型
        // 由于下面要用到这个属性，所以先用变量保存一下
        let number = Number(num);
        if (number >= 1 && Number.isInteger(number)) {
          this.sd[idx].num = number;
        } else {
          this.sd[idx].num = 1;
        }
      },
    },
  };
  </script>
  
  <style>
  td {
    text-align: center;
    padding: 5px;
    /* pointer-events: none; */
    /* 设置字体间距 */
    /* letter-spacing: 2px; */
  }
  input {
    outline: none;
    border: none;
  }
  </style>
  